/*
 * @Description: 爬取图片  
 * @Autor: sy
 * @Date: 2021-06-04 16:53:11
 * @LastEditors: sy
 * @LastEditTime: 2021-06-04 19:11:56
 */
const cheerio = require("cheerio")
const axios = require("axios")
const fs = require("fs")
const path = require("path")


let http = "https://fabiaoqing.com/bqb/detail/id/1391.html"
let mypath = "img"
axios.get(http).then((res) => {
   // 解析html 文档
   let $ = cheerio.load(res.data)
   $('.swiper-wrapper .swiper-slide a img').each((i, ele) => {
      let title = $(ele).attr('title');
      let url = $(ele).attr('data-original');
      console.log(url)
      fs.mkdir(`./${mypath}/` + title, function (err) {
         if (err) {
            console.log(err)
         } else {
            console.log('目录创建成功')
            //单个图片的url titlw
            parsePage(url, title, i)
         }
      })

   })
})

// 下载图片
async function parsePage(url, title, i) {
   // 当前图片url
   let exname = path.extname(url)
   //创建图片写入流 
   let ws = fs.createWriteStream(`./${mypath}/${title}/${title}-${i}${exname}`)
   await axios.get(url, { responseType: "stream" }).then((res) => {
      res.data.pipe(ws)//通过管道写入

   })
}

// 获取页面总数
